/*
 * Copyright (C) 2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;
using System.IO;

namespace DCSharp.Hashing
{
	/// <summary>
	/// Makes the leaves of a <see cref="HashTree"/> readable from a stream.
	/// </summary>
	public class HashTreeInputStream : Stream
	{
		private MemoryStream stream;

		/// <summary>
		/// Initializes a new <see cref="HashTreeInputStream"/> instance.
		/// </summary>
		/// <param name="hashTree">The <see cref="HashTree"/> to get the leaves from.</param>
		public HashTreeInputStream(HashTree hashTree) : base()
		{
			if (hashTree == null)
			{
				throw new ArgumentNullException("hashTree");
			}

			byte[][] leaves = hashTree.Leaves;
			stream = new MemoryStream(leaves.Length * hashTree.HashSize);

			foreach (byte[] leaf in leaves)
			{
				stream.Write(leaf, 0, leaf.Length);
			}
			stream.Flush();
			stream.Position = 0;
		}

		#region Properties

		public override bool CanRead
		{
			get { return true; }
		}

		public override bool CanSeek
		{
			get { return true; }
		}

		public override bool CanWrite
		{
			get { return false; }
		}

		public override long Position
		{
			get { return stream.Position; }
			set { stream.Position = value; }
		}

		public override long Length
		{
			get { return stream.Length; }
		}

		#endregion

		#region Methods

		public override int Read(byte[] buffer, int offset, int count)
		{
			return stream.Read(buffer, offset, count);
		}

		public override void SetLength (long value)
		{
			throw new NotSupportedException();
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			return stream.Seek(offset, origin);
		}

		public override void Flush()
		{
			throw new NotSupportedException();
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException();
		}

		protected override void Dispose(bool disposing)
		{
			stream.Dispose();
			base.Dispose(disposing);
		}

		#endregion
	}
}
